package createThread.cn.tedu.threaddemo.test9;

/**
 * 饿汉式单例模式
 */
class SingletonHunger{

    private static SingletonHunger instance = new SingletonHunger();

    private SingletonHunger() {};

    public static SingletonHunger getInstance(){
        return instance;
    }
}

/**
 * 懒汉式单例模式
 */
class SingletonLazy{
    private volatile static SingletonLazy instance = null;

    private SingletonLazy(){};
    private static final Object lock = new Object();
    public static SingletonLazy getInstance(){
        if(instance == null){
            synchronized (lock){
                if(instance == null){
                    instance = new SingletonLazy();
                }
            }
        }
        return instance;
    }
}

public class Demo1 {
    public static void main(String[] args) {
        Thread 饿汉式1 = new Thread(()->{
           SingletonHunger 实例1 = SingletonHunger.getInstance();
           SingletonHunger 实例2 = SingletonHunger.getInstance();
            System.out.println("实例一和实列二相等吗? " + (实例1 == 实例2));
        });
        Thread 饿汉式2 = new Thread(()->{
            SingletonHunger 实例1 = SingletonHunger.getInstance();
            SingletonHunger 实例2 = SingletonHunger.getInstance();
            System.out.println("实例一和实列二相等吗? " + (实例1 == 实例2));
        });
        饿汉式1.start();
        饿汉式2.start();
    }
}
